# -*- coding: utf-8 -*-
import socket,time,random,os

import json,sys
ROOT=os.path.abspath(os.path.dirname(os.path.abspath(__file__))+"/../")
sys.path.append(os.path.abspath(ROOT+"/libs"))
from common import *
# ipv4        SOCK_DGRAM指定了这个Socket的类型是UDP

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
# 绑定 客户端口和地址:
conf={}
confPath=ROOT+"/conf/conf.json"
with open(confPath,"r") as f:
    conf=json.load(f)
s.bind(('', conf["udp_port"]))
key="HKLHD&R^%*TIGDKGJDGKDFH_)(1872yw"
print('Bind UDP on 9999...')

def execCmd(args):
    with os.popen(args, "r", -1) as f:
        return (f.read())
while True:
    # 接收数据 自动阻塞 等待客户端请求:
    data, addr = s.recvfrom(1024)
    data=data.strip()
    errMsg=""
    msg=""
    print("Received %s:%s" % (addr, data))
    if len(data)>0:
        if data[0]=='{':
            data=json.loads(data)
            if ('n' in data) and ('t' in data) and ('s' in data):
                if not checkTime(data['t']):
                    errMsg="expired time"
                    
                    warn("expired time\n")
                    
                elif not checkNonce(data['n']):
                    errMsg="reduplicate nonce"
                        
                elif data['s']==hash(key,data['t'],data['n']):
                    info("verifyed")
                    if 'c' in data:
                        msg=(execCmd(data['c']))
                
                else:
                    errMsg=("invalid sign %s" % data)
                        
            else:
                errMsg=("invalid message %s" % data)
        #print message        
        elif  data[0]=='#':
            print(data[1:])         
            
    else:
       errMsg=("invalid data %s" % data)
    if len(errMsg)>0:
        print(errMsg)
        s.sendto(bytes(errMsg),addr)
    elif len(msg)>0:
        s.sendto(bytes(msg),addr)    

